# coding:utf8
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import time
from PIL import Image
import numpy as np
import pandas as pd
from pytesseract import *


def rgb(im):
    width, heigth = im.size
    data = np.zeros((heigth, width))
    aa = []
    for w in range(width):
        for h in range(heigth):
            y, cb, cr = im.getpixel((w, h))
            data[h, w] = (y+cb+cr) / 3
            aa.append((y+cb+cr) / 3)
    data = pd.DataFrame(data)
    aa = pd.Series(aa)
    return aa, data


def topliangdu(liangdu, biaozhun = 1):
    c = liangdu.value_counts()
    return list(c[c > biaozhun].index)


def liangdutianbai(im, mubiao):
    width, heigth = im.size
    for w in range(width):
        for h in range(heigth):
            y, cb, cr = im.getpixel((w, h)) #提取点(10,10)位置的亮度、蓝色分量、红色分量的值。
            tmp = (y + cb + cr) / 3
            if tmp not in mubiao:
                im.putpixel([w, h], (255, 255, 255))
                print(tmp)
    im.save('erzhihua.png')
    return im


def tongse(im):
    '''验证码验证文字的单个文字同色时，处理。'''
    global aa, data
    aa, data = rgb(im)
    mubiao = topliangdu(aa)
    im = liangdutianbai(im, mubiao)
    img_grey = im.convert('L')
    return img_grey


def erzhihua(im, point=127):
    '''图片二值化处理'''
    img_grey = im.convert('L')
    threshold = point
    table = []
    for i in range(256):
        if i < threshold:
            table.append(0)
        else:
            table.append(1)
    img_out = img_grey.point(table, '1')
    img_out.save('tmp.bmp')
    return img_out


url = 'http://202.201.252.49/'
driver = webdriver.Chrome()
driver.get(url)
# driver.maximize_window()
time.sleep(2)
driver.switch_to.frame(driver.find_element_by_xpath('/html/body/table/tbody/tr[3]/td[2]/div[1]/table/tbody/tr/td/iframe'))
element = driver.find_element_by_xpath('//*[@id="txt_sdertfgsadscxcadsads"]')
element.click()
driver.get_screenshot_as_file('suoyou.png')
img = Image.open('suoyou.png')
region = (178, 220, 255, 238) #77x18 20yige
cropImg = img.crop(region)
cropImg.save('yanzhengma.png')
region = (180, 220, 200, 238)
cropImg = img.crop(region)
cropImg.save('1.png')
region = (197, 220, 216, 238)
cropImg = img.crop(region)
cropImg.save('2.png')
region = (216, 220, 235, 238)
cropImg = img.crop(region)
cropImg.save('3.png')
region = (235, 220, 255, 238)
cropImg = img.crop(region)
cropImg.save('4.png')
img = Image.open('yanzhengma.png')
e = tongse(img)
text = image_to_string(erzhihua(img))
print(type(text))
print(len(text))
print(text)
driver.close()